package com.lwp.test.myevent;

import com.lwp.test.myevent.listener.MyEventListener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 依赖 spring 扫描所有自定监听器注解
 */
@Component
public class AppConfigScanListener implements ApplicationListener<ApplicationContextEvent> {

    @Override
    public void onApplicationEvent(ApplicationContextEvent applicationContextEvent) {

//        Map<String, Object> beanMap = new LinkedHashMap<>();
        ApplicationContext applicationContext = applicationContextEvent.getApplicationContext();
        // 扫描所有P3自定义监听类,例 applicationContext.getBeansWithAnnotation(Component.class);
        // 依赖 spring 注解，在其注册的类上扫描 MyEventListener 注解 。 beansWithAnnotation 为 LinkedHashMap
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(com.lwp.test.myevent.annotation.MyEventListener.class);
        System.out.println(beansWithAnnotation);
        hanlder(beansWithAnnotation);
    }

    /**
     * 将自定义监听器放入应用监听上下文中
     * @param beansWithAnnotation
     */
    public void hanlder(Map<String, Object> beansWithAnnotation) {
        Map<String, MyEventListener> map = new LinkedHashMap<>();
        Iterator<Map.Entry<String, Object>> it= beansWithAnnotation.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String, Object> entry = it.next();
            System.out.println("key:"+entry.getKey()+" "
                    +"Value:"+entry.getValue());
            if (entry.getValue() instanceof MyEventListener) {
                map.put(entry.getKey(), (MyEventListener) entry.getValue());
            }
        }
        MyEventContext.setEventListenerMap(map);
    }
}
